<template>
	<div class="app-org-sector">
		<a-dropdown>
			<div class="orgsector">
				<span>{{ selectedOrgName }}</span>
				<DownOutlined v-if="selectedOrgArray.length > 0" />
			</div>
			<template #overlay>
				<a-menu class="menu" @click="orgSelect">
					<a-menu-item
						v-for="(item, index) in selectedOrgArray"
						:key="item.organization_id"
					>
						{{ item.organization_name }}
					</a-menu-item>
				</a-menu>
			</template>
		</a-dropdown>
	</div>
</template>

<script lang="ts" setup>
import { Http } from '@/http';
import { useAppStoreWithOut } from '@/store';
import { Ref } from 'vue';
import { DownOutlined } from '@ant-design/icons-vue';

import { OrgSectorProps } from './orgsector';
import { getSessionStorage, IParam, setSessionStorage } from '@/core';
const props = defineProps(OrgSectorProps);

/**
 * 注入加载行为
 *
 * @memberof AppOrgSector
 */
const reload: Function | undefined = inject('reload');

/**
 * 选中组织部门id
 *
 * @type {string}
 * @memberof AppOrgSector
 */
const selectedOrgId: Ref<string> = ref('');

/**
 * 选中组织部门名称
 *
 * @type {string}
 * @memberof AppOrgSector
 */
const selectedOrgName: Ref<string> = ref('');

/**
 * 组织部门名称数组
 *
 * @type {Array<any>}
 * @memberof AppOrgSector
 */
const selectedOrgArray: Ref<Array<any>> = ref([]);

/**
 * 获取数据
 *
 * @memberof AppOrgSector
 */
const getData = () => {
    const { context: appContext} = App.getAppData();
    if (appContext && appContext.memberof && appContext.memberof.length > 0) {
        selectedOrgArray.value = appContext.memberof;
        const activeOrgData = getSessionStorage('activeOrgData');
        setActiveData(activeOrgData || appContext.memberof[0]);
    }
};

/**
 * 设置激活数据
 *
 * @memberof AppOrgSector
 */
const setActiveData = (item: IParam) => {
    selectedOrgName.value = item.organization_name;
    selectedOrgId.value = item.organization_id;
}

onMounted(() => {
	getData();
});

/**
 * 更新仓库部门信息
 *
 * @memberof AppOrgSector
 */
const updateStoreOrgData = (data: any) => {
	const appData = App.getAppData();
	let _context: any = appData.context;
	Object.assign(_context, data);
	Object.assign(appData, { context: _context });
	const { addAppData } = useAppStoreWithOut();
	addAppData(appData);
};

/**
 * 选择组织部门回调
 *
 * @memberof AppOrgSector
 */
const orgSelect = (item: IParam) => {
    const { key } = item;
	if (Object.is(key, selectedOrgId.value)) {
		return;
	}
    const activeOrgData = selectedOrgArray.value.find((item: IParam) => Object.is(key, item.organization_id));
    if (activeOrgData) {
        setSessionStorage('activeOrgData', {organization_name: activeOrgData.organization_name, organization_id: activeOrgData.organization_id});
        setActiveData(activeOrgData);
    }
};
</script>
